package com.sangeng.service.impl;

import com.sangeng.config.RedisCache;
import com.sangeng.entity.GlcUser;
import com.sangeng.entity.ResponseResult;
import com.sangeng.entity.User;
import com.sangeng.service.GlcAuthService;
import com.sangeng.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.net.PasswordAuthentication;
import java.util.HashMap;

@Service
public class GlcAuthServiceImpl implements GlcAuthService {



    @Autowired
    private  AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken passwordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());

        Authentication authenticate = authenticationManager.authenticate(passwordAuthenticationToken);

        if (authenticate == null ){
            throw new RuntimeException("认证失败");
        }
        GlcUser glcUser = (GlcUser) authenticate.getPrincipal();
        String userId = glcUser.getUser().getId().toString();

        //存入 redis
        redisCache.setCacheObject("userId:"+userId,glcUser);

        String jwt = JwtUtil.createJWT(userId);
        //把token响应给前端
        HashMap<String,String> map = new HashMap<>();
        map.put("token",jwt);
        return new ResponseResult(200,"登陆成功",map);

    }
}
